<template>
  <div
    :class="className"
    :style="{height: height,width: width}"
  />
</template>

<script>
import echarts from 'echarts' // echarts theme
import { debounce } from '@/utils'
require('echarts/theme/macarons')

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '530px'
    },
    sumCase: {
      type: Object
    },
    majorCase: {
      type: Object
    },
    parentObject: {
      type: Object
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object
    }
  },
  data() {
    return {
      chart: null,
      parentData: '',
      defaultData: {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          left: 'center',
          selectedMode: false,
          bottom: '10',
          data: ['Industries', 'Technology', 'Forex', 'Gold', 'Forecasts']
        },
        calculable: true,
        series: [{
          name: 'Default Test Data',
          type: 'pie',
          roseType: 'radius',
          radius: [35, 75],
          center: ['50%', '38%'],
          data: [{
            value: 320,
            name: 'Industries'
          }, {
            value: 240,
            name: 'Technology'
          }, {
            value: 149,
            name: 'Forex'
          }, {
            value: 100,
            name: 'Gold'
          }, {
            value: 59,
            name: 'Forecasts'
          }],
          animationEasing: 'cubicInOut',
          animationDuration: 2600
        }]
      }
    }
  },
  watch: {
    sumCase: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    },
    majorCase: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    },
    parentObject: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    },
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.parentData = this.sumCase || this.majorCase || this.parentObject
    this.initChart()
    this.__resizeHanlder = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHanlder)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    if (this.autoResize) {
      window.removeEventListener('resize', this.__resizeHanlder)
    }
    window.removeEventListener('resize', this.__resizeHanlder)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    setOptions({
      date,
      returnedCount,
      returnedMoney
    } = {}) {
      console.table(returnedCount, returnedMoney)
      this.chart.setOption({
        backgroundColor: 'white',
        xAxis: {
          data: date,
          boundaryGap: false,
          axisTick: {
            show: true
          }
        },
        grid: {
          left: 25,
          right: 35,
          bottom: 40,
          top: 30,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          padding: [5, 10]
        },
        yAxis: [{
          type: 'value',
          // show: true,
          name: '案件回款金额',
          // nameTextStyle: {
          //     padding: [0 , 0, 0, 19]
          // },
          // nameGap: 5,
          nameLocation: 'end',
          min: 0,
          max: Math.max.apply(Math, returnedMoney.map(m => m >> 0)),
          // interval: 1,
          position: 'left',
          axisLine: {
            lineStyle: {
              color: '#87CBFF'
            }
          },
          axisLabel: {
            formatter: '{value}'
          }
          // max: 500
        }, {
          type: 'value',
          name: '案件回款数量',
          min: 0,
          max: Math.max.apply(Math, returnedCount),
          minInterval: 1,
          position: 'right',
          axisLine: {
            lineStyle: {
              color: '#B15E97'
            }
          },
          axisLabel: {
            formatter: '{value}'
          }
        }],
        legend: {
          show: true,
          orient: 'horizontal',
          // right: 20,
          // top: 60,
          bottom: 0,
          data: ['案件回款金额', '回款案件数量'],
          textStyle: {
            color: '#494B4D',
            fontSize: 12
          }
        },
        series: [{
          name: '案件回款金额',
          smooth: false,
          symbol: 'rectangle',
          symbolSize: 6,
          itemStyle: {
            normal: {
              color: 'rgba(135,203,255,1)',
              lineStyle: {
                color: 'rgba(135,203,255,1)',
                width: 1
                // shadowColor: 'rgba(0, 0, 0, 0.3)',
                // shadowBlur: 5
              },
              areaStyle: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                    offset: 0,
                    color: 'rgba(135,203,255,0.3)'
                  }, {
                    offset: 1,
                    color: 'rgba(135,203,255,0.3)'
                  }],
                  globalCoord: false
                }
              }
            }
          },
          type: 'line',
          data: returnedMoney,
          animationDuration: 2800,
          animationEasing: 'quadraticOut'
        }, {
          name: '回款案件数量',
          smooth: false,
          symbol: 'rectangle',
          symbolSize: 6,
          itemStyle: {
            normal: {
              color: 'rgba(177,94,151,1)',
              lineStyle: {
                color: 'rgba(177,94,151,1)',
                width: 1
                // shadowColor: 'rgba(0, 0, 0, 0.3)',
                // shadowBlur: 5
              },
              areaStyle: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                    offset: 0,
                    color: 'rgba(177,94,151,0.2)'
                  }, {
                    offset: 1,
                    color: 'rgba(177,94,151,0.2)'
                  }],
                  globalCoord: false
                }
              }
            }
          },
          yAxisIndex: 1,
          type: 'line',
          data: returnedCount,
          animationDuration: 2800,
          animationEasing: 'cubicInOut'
        }]
      })
    },
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      const cData = this.chartData || {}
      console.log('this.chartData:', cData, this.chartData)
      this.setOptions(cData)
    },
    setOptions1(obj) {
      // common config
      obj.legend && (obj.legend.selectedMode = false)
      const currColors = location.hash.split('=')[1] && decodeURIComponent(location.hash.split('=')[1]).replace(/\[|\]|\'/img, '').split(',') || ''
      obj.color = currColors || obj.color
      this.chart.setOption(obj)
    },
    initChart1() {
      console.log('parentData:', this.parentData)
      this.chart = echarts.init(this.$el, 'macarons')
      if (this.parentData) {
        this.chart.setOption(this.parentData)
        this.chart.on('finished', arg => {
          /* console.log('chartDataUrl:', this.chart.getDataURL({
                        type: 'jpg',
                        pixelRatio: 1
                    })) */
        })
        return
      }
      // default test data
      this.chart.setOption(this.defaultData)
    }
  }
}
</script>
